using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
using Microsoft.Dss.Core.DsspHttpUtilities;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using Microsoft.Robotics.PhysicalModel.Proxy;
using System;
using System.Net;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Security.Permissions;
using xml = System.Xml;
using W3C.Soap;

using bumper = Microsoft.Robotics.Services.ContactSensor.Proxy;
using vex = VEXRobotics.Proxy;
using submgr = Microsoft.Dss.Services.SubscriptionManager;

namespace VEXService.LimitSwitch
{
    /// <summary>
    /// ContactSensor Port
    /// </summary>
    [ServicePort]
    public class VEXLimitSwitchOperations : PortSet<
        DsspDefaultLookup,
        DsspDefaultDrop,
        HttpGet,
        HttpPost,
        Get,
        bumper.Replace,
        bumper.Update,
        bumper.ReliableSubscribe,
        bumper.Subscribe
        >
    {
    }

    /// <summary>
    /// Get the VEX Limit Sensor State
    /// </summary>
    [Description("Gets the current state of the VEX Limit Sensor.")]
    public class Get : Get<GetRequestType, PortSet<VEXContactSensor, Fault>>
    {
    }

    /// <summary>
    /// Additional configuration which is necessary to 
    /// configure any VEX sensor as a Limit Switch.
    /// </summary>
    [DataContract]
    public class VEXContactSensor : IDssSerializable, ICloneable
    {
        private vex.SensorPort _sensorPort;
        private string _name;
        private bool _pressed;
        private DateTime _TimeStamp;
        private Pose _Pose;

        public VEXContactSensor()
        {
            _TimeStamp = DateTime.MinValue;
            _Pose = new Pose();
        }

        /// <summary>
        /// Indentifies the VEX Sensor Port in which this sensor is plugged.
        /// </summary>
        [DataMember]
        [Description("The sensor port in which the switch is plugged.")]
        public vex.SensorPort SensorPort
        {
            get { return _sensorPort; }
            set { _sensorPort = value; }
        }

        /// <summary>
        /// The name of this sensor
        /// </summary>
        [DataMember]
        [Description("The descriptive name for this sensor.")]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        // Summary:
        //     Whether the button is currently pressed
        [Browsable(false)]
        [Description("Whether the button has been pressed")]
        [DataMember(Order = -1)]
        public bool Pressed
        {
            get { return _pressed; }
            set { _pressed = value; }
        }

        //
        // Summary:
        //     Timestamp of this sample
        [DefaultValue(typeof(DateTime), "0001-01-01T00:00:00")]
        [Description("Identifies the timestamp of the limit switch reading.")]
        [Browsable(false)]
        [DataMember(Order = -1, XmlOmitDefaultValue = true)]
        public DateTime TimeStamp
        {
            get { return _TimeStamp; }
            set { _TimeStamp = value; }
        }

        /// <summary>
        /// Pose of the limit switch
        /// </summary>
        [DataMember]
        [Description("The position and orientation of the limit switch.")]
        public Pose Pose
        {
            get { return _Pose; }
            set { _Pose = value; }
        }


        /// <summary>
        /// Transform current state to the specified generic state.
        /// </summary>
        /// <param name="genericState"></param>
        /// <returns></returns>
        public bumper.ContactSensor ToGenericState(bumper.ContactSensor genericState)
        {
            genericState.HardwareIdentifier = (int)this.SensorPort;
            genericState.Name = this.Name;
            genericState.Pose = this.Pose;
            genericState.Pressed = this.Pressed;
            genericState.TimeStamp = this.TimeStamp;
            return genericState;
        }
        public bumper.ContactSensorArrayState ToGenericState(bumper.ContactSensorArrayState genericState)
        {
            genericState.Sensors.Clear();
            bumper.ContactSensor myState = new bumper.ContactSensor();
            genericState.Sensors.Add(this.ToGenericState(myState));
            return genericState;
        }

        /// <summary>
        /// Copy generic state to this state, transforming data members.
        /// </summary>
        /// <param name="genericState"></param>
        public void FromGenericState(bumper.ContactSensor genericState)
        {
            this.Name = genericState.Name;
            this.Pose = genericState.Pose;
            this.Pressed = genericState.Pressed;
            this.SensorPort = (vex.SensorPort)genericState.HardwareIdentifier;
            this.TimeStamp = genericState.TimeStamp;
        }


        #region IDssSerializable

        /// <summary>
        /// Copy To Analog Input sensor state
        /// </summary>
        public virtual void CopyTo(IDssSerializable target)
        {
            VEXContactSensor typedTarget = target as VEXContactSensor;

            if (typedTarget == null)
                throw new ArgumentException("CopyTo({0}) requires type {0}", this.GetType().FullName);

            typedTarget.Name = this.Name;
            typedTarget.Pose = this.Pose;
            typedTarget.Pressed = this.Pressed;
            typedTarget.SensorPort = this.SensorPort;
            typedTarget.TimeStamp = this.TimeStamp;
        }

        /// <summary>
        /// Clone the VEX Limit Switch State
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            VEXContactSensor clone = new VEXContactSensor();
            clone.Name = this.Name;
            clone.Pose = this.Pose;
            clone.Pressed = this.Pressed;
            clone.SensorPort = this.SensorPort;
            clone.TimeStamp = this.TimeStamp;

            return clone;
        }

        /// <summary>
        /// Serialize
        /// </summary>
        public virtual void Serialize(System.IO.BinaryWriter writer)
        {
            writer.Write(this.Name);
            Pose.Serialize(writer);
            writer.Write(this.Pressed);
            writer.Write((int)this.SensorPort);
            Microsoft.Dss.Services.Serializer.BinarySerializationHelper.SerializeDateTime(TimeStamp, writer);
        }

        /// <summary>
        /// Deserialize
        /// </summary>
        public virtual object Deserialize(System.IO.BinaryReader reader)
        {
            Name = reader.ReadString();
            Pose.Deserialize(reader);
            Pressed = reader.ReadBoolean();
            SensorPort = (vex.SensorPort)reader.ReadInt32();
            TimeStamp = Microsoft.Dss.Services.Serializer.BinarySerializationHelper.DeserializeDateTime(reader);

            return this;
        }
        #endregion
    }

    /// <summary>
    /// VEX Limit Switch Contract 
    /// </summary>
    public sealed class Contract
    {
        public const string Identifier = "http://schemas.vexrobotics.com/2011/09/vexservice.limitswitch.html";
    }


    [Contract(Contract.Identifier)]
    [AlternateContract(bumper.Contract.Identifier)]
    [DisplayName("VEX Limit Switch")]
    [Description("Provides access to the VEX Limit Switch.")]
    [DssServiceDescription("http://msdn.microsoft.com/en-us/library/dd145249.aspx")]
    [DssCategory(vex.VEXCategories.VEX)]
    public class VEXLimitSwitch : DsspServiceBase
    {
        /// <summary>
        /// XSLT Transform to use for display
        /// </summary>
        [EmbeddedResource("VEXService.Config.LimitSwitch.xslt")]
        private string _transform = null;

        /// <summary>
        /// Sensor state
        /// </summary>
        [InitialStatePartner(Optional = true, ServiceUri = ServicePaths.Store + @"/VEX.LimitSwitch.config.xml")]
        private VEXContactSensor _State = new VEXContactSensor();

        /// <summary>
        /// Service port
        /// </summary>
        [ServicePort("/VEX/LimitSwitch", AllowMultipleInstances = true)]
        private VEXLimitSwitchOperations _mainPort = new VEXLimitSwitchOperations();

        /// <summary>
        /// Port to talk with the VEX controller
        /// </summary>
        [Partner("VEX", Contract = vex.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate,
            Optional = false)]
        private vex.VEXOperations _vexPort = new vex.VEXOperations();

        // VEX Notifications
        vex.VEXOperations _notificationPort = new vex.VEXOperations();

        // Create a local ContactSensor for convenience
        [AlternateServicePort("/contactsensor",
            AllowMultipleInstances = true,
            AlternateContract = bumper.Contract.Identifier)]
        private bumper.ContactSensorArrayOperations _genericPort = new bumper.ContactSensorArrayOperations();


        /// <summary>
        /// HTTP helper
        /// </summary>
        DsspHttpUtilitiesPort _httpUtilities = new DsspHttpUtilitiesPort();

        /// <summary>
        /// Subscription manager
        /// </summary>
        [Partner("SubMgr", Contract = submgr.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.CreateAlways,
            Optional = false)]
        private submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="creationPort"></param>
        public VEXLimitSwitch(DsspServiceCreationPort creationPort)
            : base(creationPort)
        {
        }

        #region Initialization Code

        /// <summary>
        /// Startup
        /// </summary>
        protected override void Start()
        {
            LogVerbose(LogGroups.Console, "Configuring VEX Contact Sensor... ");

            #region Initialize Service State
            if (_State == null)
            {
                _State = new VEXContactSensor();
                SaveState(_State);
            }
            #endregion

            base.Start();

            #region Initialize Service State
            // Reset the controller to know about our configuration
            Port<bool> donePort = new Port<bool>();
            SpawnIterator<Port<bool>>(donePort, SetLimitConnection);
            Activate(Arbiter.Receive(false, donePort,
                delegate(bool success)
                {
                    if (success)
                    {
                        // display HTTP service Uri
                        LogInfo(LogGroups.Console, "Service uri: ");
                    }
                    else
                    {
                        LogError(LogGroups.Console, "VEX Limit Switch service failed to start.");
                        _mainPort.Post(new DsspDefaultDrop());
                    }
                }));
            #endregion

            // Needed for HttpPost
            _httpUtilities = DsspHttpUtilitiesService.Create(Environment);
        }

        /// <summary>
        /// Set the configuration
        /// </summary>
        /// <param name="donePort"></param>
        /// <returns></returns>
        private IEnumerator<ITask> SetLimitConnection(Port<bool> donePort)
        {
            bool serviceSuccess = true;

            // Configure default state
            if (_State.SensorPort == vex.SensorPort.SensorPort_None)
            {
                LogError(_State.Name + ": No sensor port selected");
                serviceSuccess = false;
            }
            else
            {
                // Configure default state
                vex.SelectivePortConfigure newConfig = new vex.SelectivePortConfigure();
                newConfig.Body.Port = _State.SensorPort;
                newConfig.Body.Type = vex.SensorDefinition.SensorType.Limit;

                _vexPort.Post(newConfig);
                yield return Arbiter.Choice(newConfig.ResponsePort,
                    delegate(DefaultReplaceResponseType response)
                    {
                    },
                    delegate(Fault fault)
                    {
                        serviceSuccess = false;
                        LogError(LogGroups.Console, "Failed to update VEX service configuration", fault);
                    });

                // Subscribe to VEX for notifications
                if (serviceSuccess)
                {
                    serviceSuccess = false;
                    SaveState(_State);
                    Port<bool> subscribeDonePort = new Port<bool>();
                    SpawnIterator<Port<bool>>(subscribeDonePort, SubscribeToVEX);
                    yield return (Arbiter.Receive<bool>(false, subscribeDonePort,
                        delegate(bool success)
                        {
                            serviceSuccess = success;
                        }));
                }
            }

            yield break;
        }

        /// <summary>
        /// Subscribe to appropriate sensor type and port on VEX
        /// Hook up notifications
        /// and then post success or failure
        /// <param name="successPort"></param>
        /// </summary>
        private IEnumerator<ITask> SubscribeToVEX(Port<bool> successPort)
        {
            //create a custom subscription request
            vex.CustomSubscribeRequestType request = new vex.CustomSubscribeRequestType();

            //select only the sensor and port we want
            //NOTE: this name must match the VEX sensor name.
            request.Sensors = new List<vex.SensorDefinition>();

            vex.SensorDefinition sensor = new vex.SensorDefinition();
            sensor.Type = vex.SensorDefinition.SensorType.Button;
            sensor.Port = _State.SensorPort;
            request.Sensors.Add(sensor);

            //Subscribe to the VEX and wait for a response
            bool subscribed = false;
            yield return
                Arbiter.Choice(_vexPort.SelectiveSubscribe(request, _notificationPort),
                    delegate(SubscribeResponseType Rsp)
                    {
                        //Subscription was successful, start listening for sensor change notifications
                        Activate(
                            Arbiter.Receive<vex.Update>(true, _notificationPort, SensorNotificationHandler)
                        );

                        // Update our state with subscription status
                        subscribed = true;
                    },
                    delegate(Fault fault)
                    {
                        LogError("Limit Switch subscription failed", fault);
                        successPort.Post(false);
                    }
                );

            successPort.Post(subscribed);
            yield break;
        }

        #endregion

        #region Internal Port Handlers

        /// <summary>
        /// Handle sensor update message from VEX
        /// </summary>
        private void SensorNotificationHandler(vex.Update notify)
        {
            //update state
            bool newContactValue = _State.Pressed;
            if (_State.SensorPort != vex.SensorPort.SensorPort_None)
            {
                ushort value = notify.Body.PortSensors.Sensors[(int)_State.SensorPort - 1].Value;
                newContactValue = (value == 0);
                _State.TimeStamp = DateTime.Now;
            }
            bool changed = (_State.Pressed != newContactValue);
            _State.Pressed = newContactValue;

            if (changed)
            {
                bumper.ContactSensor sensor = new bumper.ContactSensor((int)_State.SensorPort, _State.Name);
                SendNotification<bumper.Update>(_subMgrPort, _State.ToGenericState(sensor));
            }
        }



        #endregion

        #region Standard Operation Handlers

        /// <summary>
        /// Get the state
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public IEnumerator<ITask> GetHandler(Get get)
        {
            get.ResponsePort.Post(_State);
            yield break;
        }

        /// <summary>
        /// Get the state
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> GetHandler(bumper.Get get)
        {
            bumper.ContactSensorArrayState genericState = new bumper.ContactSensorArrayState();
            bumper.ContactSensor genericSensor = new bumper.ContactSensor();
            _State.ToGenericState(genericSensor);
            genericState.Sensors.Add(genericSensor);
            get.ResponsePort.Post(genericState);
            yield break;
        }

        /// <summary>
        /// Get the state to HTTP display
        /// </summary>
        /// <param name="httpGet">Response port to post the state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        [ServiceHandler(ServiceHandlerBehavior.Concurrent, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            httpGet.ResponsePort.Post(new HttpResponseType(
                HttpStatusCode.OK,
                _State,
                _transform)
            );
            yield break;
        }


        /// <summary>
        /// HttpPost Handler
        /// </summary>
        /// <param name="submit"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost)
        {
            // Use helper to read form data
            ReadFormData readForm = new ReadFormData(httpPost);
            _httpUtilities.Post(readForm);

            // Wait for result
            Activate(Arbiter.Choice(readForm.ResultPort,
                delegate(NameValueCollection parameters)
                {
                    if (parameters["Name"] != null)
                    {
                        // Update our state variables
                        _State.Name = parameters["Name"];
                    }
                    HttpPostSuccess(httpPost);
                },
                delegate(Exception fault)
                {
                    LogError(fault.Message);
                    HttpPostFailure(httpPost, fault.Message);
                })
            );
            yield break;
        }

        /// <summary>
        /// Send Http Post Success Response
        /// </summary>
        /// <param name="httpPost"></param>
        private void HttpPostSuccess(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.OK, _State, _transform);
            httpPost.ResponsePort.Post(rsp);
        }

        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        /// <param name="httpPost"></param>
        /// <param name="failureReason"></param>
        private static void HttpPostFailure(HttpPost httpPost, string failureReason)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.ExpectationFailed, failureReason);
            httpPost.ResponsePort.Post(rsp);
        }
        
        /// <summary>
        /// Replace the state with the given update
        /// </summary>
        /// <param name="replace">Replacement state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ReplaceHandler(bumper.Replace replace)
        {
            if (replace.Body.Sensors.Count != 1)
            {
                Fault fault = Fault.FromException(new InvalidOperationException("Invalid number of sensors"));
                replace.ResponsePort.Post(fault);
                yield break;
            }
            if ((int)_State.SensorPort != replace.Body.Sensors[0].HardwareIdentifier)
            {
                Fault fault = Fault.FromException(new InvalidOperationException("Cannot reassign sensor ports"));
                replace.ResponsePort.Post(fault);
                yield break;
            }
            _State.FromGenericState(replace.Body.Sensors[0]);
            SaveState(_State);

            bumper.ContactSensorArrayState genericState = new bumper.ContactSensorArrayState();
            genericState.Sensors = new List<bumper.ContactSensor>();
            SendNotification<bumper.Replace>(_subMgrPort, _State.ToGenericState(genericState));
            replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
            yield break;
        }

        /// <summary>
        /// Subscribe to updates
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> SubscribeHandler(bumper.Subscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    ProcessSubscribeResponse(subscribe.Body.Subscriber);
                },
                delegate(Exception fault)
                {
                    LogError(fault);
                }
            );
        }

        /// <summary>
        /// ReliableSubscribe Handler
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ReliableSubscribeHandler(bumper.ReliableSubscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    ProcessSubscribeResponse(subscribe.Body.Subscriber);
                },
                delegate(Exception fault)
                {
                    LogError(fault);
                }
            );
        }

        /// <summary>
        /// Handle the Update message
        /// </summary>
        /// <param name="update"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> UpdateHandler(bumper.Update update)
        {
            _State.FromGenericState(update.Body);

            update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }

        #endregion

        #region Subroutines

        /// <summary>
        /// Process the subscription response
        /// </summary>
        /// <param name="subscriber"></param>
        private void ProcessSubscribeResponse(string subscriber)
        {
            bumper.ContactSensorArrayState genericState = new bumper.ContactSensorArrayState();
            genericState.Sensors = new List<bumper.ContactSensor>();
            SendNotification<bumper.Replace>(_subMgrPort, subscriber, _State.ToGenericState(genericState));
        }
        #endregion
    }
}
